package com.client.Interceptor;

import com.Emplyment.context.BaseContext;
import com.Emplyment.properties.JwtProperties;
import com.Emplyment.utils.jwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class JwtToeknEmplymentInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验令牌token准确性
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //判断当前拦截到的是Controller的方法还是其他资源
        //左边的对象是否是它右边的类的实例
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        try {
            //1.从请求头中获取token
            String token = request.getHeader(jwtProperties.getAdminTokenName());
            //2.判断token是否正确
            log.info("令牌为：{}",token);
            Claims claims = jwtUtils.parseJWT(jwtProperties.getAdminSecretKey(), token);
            Long empId = Long.valueOf(claims.get("emp_id").toString());
            log.info("员工id为:{}",empId);
            BaseContext.setCurrentId(empId);
            //通过，放行

            return true;
        } catch (Exception e) {
            //不通过，直接返回状态码401
            response.setStatus(401);
            return false;
        }


    }
}
